package com.lsh.oms.worker.service.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dangdang.ddframe.job.api.JobExecutionMultipleShardingContext;
import com.dangdang.ddframe.job.plugin.job.type.simple.AbstractSimpleElasticJob;
import com.lsh.oms.core.constant.Constants;
import com.lsh.oms.core.enums.OrderStatus;
import com.lsh.oms.core.model.http.HttpMessage;
import com.lsh.oms.core.model.order.OrderHead;
import com.lsh.oms.core.model.order.OrderShippingHead;
import com.lsh.oms.core.model.order.OrderShippingHeadWithBLOBs;
import com.lsh.oms.core.proxy.service.DmallProxy;
import com.lsh.oms.core.proxy.service.TmsProxy;
import com.lsh.oms.core.redis.RedisTemplate;
import com.lsh.oms.core.service.order.OrderQueryService;
import com.lsh.oms.core.service.other.ShippingOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Project Name: lsh-oms
 *
 * @author peter
 * @date 18/2/27
 * 北京链商电子商务有限公司
 * Package:
 * desc:
 */
@Slf4j
@Component
public class BillShipNotifyDmallJop extends AbstractSimpleElasticJob {


    @Autowired
    private OrderQueryService orderQueryService;

    @Autowired
    private ShippingOrderService shippingOrderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TmsProxy tmsProxy;

    @Autowired
    private DmallProxy dmallProxy;

    @Override
    public void process(JobExecutionMultipleShardingContext jobExecutionMultipleShardingContext) {

        try {

            Integer startTime = this.getStartTime();
            log.info("【推送多点订单配送中】统计范围 {}", startTime);
            List<OrderHead> orderHeads = orderQueryService.findListByStatusRangeAndTimeRange(OrderStatus.ORDER_SORTING.getIndex(), OrderStatus.ORDER_SIGN.getIndex(), startTime);

            if (CollectionUtils.isEmpty(orderHeads)) {
                log.info("【推送多点订单配送中】需要处理的数据集合是空-" + startTime);
                return;
            }
            log.info("【推送多点订单配送中】匹配订单数量 {}", orderHeads.size());
            orderHeads = orderHeads.stream().filter(orderHead -> this.pushFilter(orderHead)).collect(Collectors.toList());
            log.info("【推送多点订单配送中】需要推送数量 {}", orderHeads.size());

            int dealNum = 0;
            for (OrderHead orderHead : orderHeads) {
                JSONObject orderext = JSON.parseObject(orderHead.getAddressInfo());
                String dmallOrderId = orderext.getString("DuoDianOrderId");

                OrderShippingHead orderShippingHead = shippingOrderService.selectOneByOrderCode(orderHead.getOrderCode(), false);
                if (null == orderShippingHead) {
                    log.info(orderHead.getOrderCode() + " 发货单未找到");
                    continue;
                }
                Long tranUid = orderShippingHead.getTransUid();
                if (null == tranUid || tranUid == 0L) {
                    log.info(orderHead.getOrderCode() + " 司机信息不存在 tranUid " + tranUid);
                    continue;
                }
                JSONArray contents = this.getTranInfo(orderShippingHead);
                if (null == contents || contents.isEmpty()) {
                    log.info(orderShippingHead.getShippingOrderId() + " 司机信息查找失败 " + orderShippingHead.getTransUid());
                    continue;
                }
                JSONObject tranInfo = contents.getJSONObject(0);
                if (null == tranInfo) {
                    log.info(orderShippingHead.getShippingOrderId() + " 司机信息查找失败 null " + orderShippingHead.getTransUid());
                    continue;
                }

                JSONObject req = new JSONObject();
                req.put("orderId", dmallOrderId);
                req.put("processTime", orderShippingHead.getActivedAt().longValue() * 1000);
                req.put("deliveryId", orderShippingHead.getTransUid());
                req.put("deliveryName", tranInfo.getString("name"));
                req.put("deliveryTel", tranInfo.getString("cellphone"));

                if (dmallProxy.pushShipDmall(req)) {
                    redisTemplate.set(Constants.PUSH_SHIPPING_TIME_KEY + orderHead.getOrderCode(), "push");
                    dealNum++;
                } else {
                    log.info("【推送多点订单配送中】失败订单号-fail {}", orderHead.getOrderCode());
                }
            }
            log.info("【推送多点订单配送中】成功推送数量 {}", dealNum);
        } catch (Exception ex) {
            log.error(Constants.PUSH_SHIPPING_TIME_KEY + " 异常", ex);
        }

    }


    /**
     * 获取司机信息
     *
     * @param orderShippingHead
     * @return
     */
    private JSONArray getTranInfo(OrderShippingHead orderShippingHead) {

        JSONArray contents = null;
        try {
            HttpMessage httpMessage = this.tmsProxy.getTranInfo("", orderShippingHead.getTransUid(), orderShippingHead.getVenderId());
            log.info(orderShippingHead.getShippingOrderId() + " 查询司机信息" + JSON.toJSONString(httpMessage));
            if (httpMessage.getStatus().equals("200")) {
                OrderShippingHeadWithBLOBs update = new OrderShippingHeadWithBLOBs();
                update.setId(orderShippingHead.getId());

                String message = httpMessage.getMessage();
                if (org.apache.commons.lang3.StringUtils.isBlank(message)) {
                    return null;
                }

                JSONObject messageJson = JSONObject.parseObject(message);
                if (null == messageJson || messageJson.getInteger("ret") != 0) {
                    return null;
                }
                contents = messageJson.getJSONArray("content");
                if (null == contents) {
                    return null;
                }
            }

        } catch (Exception ex) {
            log.error("查询司机信息 失败", ex);
            contents = null;
        }

        return contents;

    }

    /**
     * 过滤订单
     *
     * @param orderHead
     * @return
     */
    private boolean pushFilter(OrderHead orderHead) {

        if (!StringUtils.isEmpty(redisTemplate.get(Constants.PUSH_SHIPPING_TIME_KEY + orderHead.getOrderCode()))) {
            return false;
        }

        JSONObject orderext = JSON.parseObject(orderHead.getAddressInfo());
        String duoDianOrder = orderext.getString("DuoDianOrder");
        if (StringUtils.isEmpty(duoDianOrder)) {
            redisTemplate.set(Constants.PUSH_SHIPPING_TIME_KEY + orderHead.getOrderCode(), "push-no");
            return false;
        }

        if (duoDianOrder.equals("1")) {
            redisTemplate.set(Constants.PUSH_SHIPPING_TIME_KEY + orderHead.getOrderCode(), "push-no-1");
            return false;
        }

        return true;
    }

    /**
     * 统计开始时间
     *
     * @return 时间戳
     */
    private Integer getStartTime() {

        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) - 2);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
//        cal.add(Calendar.DATE, -1);

        return (int) TimeUnit.MILLISECONDS.toSeconds(cal.getTime().getTime());
    }


}
